package pwd.allen;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.configuration.FluentConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @author pwdan
 * @create 2021-09-17 14:34
 **/
public class Main {

    private static final Logger logger = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) throws IOException {
        System.out.println(String.format("user.dir=%s", System.getProperty("user.dir")));

        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(System.getProperty("user.dir") + File.separator + "dbconfig.properties"));

        } catch (IOException e) {}
        if (!properties.isEmpty()) {
            logger.info("读取Jar外部配置文件！");
        } else {
            // 不能用getResource()，否则打包后路径是xxx.jar!/...，会报FileNotFound
            properties.load(Main.class.getClassLoader().getResourceAsStream("dbconfig.properties"));
            logger.info("读取默认的配置文件！");
        }
        String url = properties.getProperty("jdbc.url");
        String username = properties.getProperty("jdbc.username");
        String password = properties.getProperty("jdbc.password");
        String schema = properties.getProperty("jdbc.schema");
        String locations = properties.getProperty("flyway.locations");

        FluentConfiguration configuration = Flyway.configure().dataSource(url, username, password)
                .locations(locations)
                .baselineOnMigrate(true)
                .ignoreMissingMigrations(true)
                .placeholderReplacement(false)
//                .outOfOrder(true)
                .cleanDisabled(true)
                .baselineVersion("0");
        if (schema != null) {
            configuration.schemas(schema);
        }
        Flyway flyway = configuration.load();

        // TODO 不知道是不是只删除flyway_schema_history中失败的记录
//        flyway.repair();

        flyway.migrate();
    }
}
